package com.cndw.kungfu.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import com.cndw.commons.util.BlankUtils;
import com.cndw.kungfu.comm.AccessInspection;
import com.cndw.kungfu.comm.CommInspection;
import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsConfig;
import com.cndw.kungfu.config.ConstantsCost;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.domain.Mail;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.domain.Union;
import com.cndw.kungfu.ext.JsonProcesser;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.StringProcesser;
import com.cndw.kungfu.ext.WordProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.goods.domain.SubPops;
import com.cndw.kungfu.model.message.GroupSendTask;
import com.cndw.kungfu.model.message.MailManager;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.kungfu.vo.MailVO;
import com.cndw.kungfu.vo.goodsvo.SubPopsVO;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;

/**
 * 短信操作
 * 
 * @author fantadust
 * @date 2011-5-11 下午04:09:19
 */
@Controller
public class MailController {
	@Autowired
	private MailManager mailManager;

	/**
	 * 读信件列表
	 * 
	 * @param session
	 * @param readMap
	 *            type,page,pageSize,action
	 * @return
	 */
	public ResponseMessage readList(Session session, Map<String, Integer> readMap) {
		long playerId = session.getUid();
		int type = readMap.containsKey("type") ? readMap.get("type") : 0;
		int page = readMap.containsKey("page") ? readMap.get("page") : 1;
		page = page <= 0 ? 1 : page;
		int pageSize = readMap.containsKey("pageSize") ? readMap.get("pageSize") : Constants.PAGE_SIZE;
		int action = readMap.containsKey("action") ? readMap.get("action") : 1;
		pageSize = pageSize == 0 ? Constants.PAGE_SIZE : pageSize;

		List<MailVO> list = mailManager.getList(playerId, type, action, (page - 1) * pageSize, pageSize);
		int counts = mailManager.getcount(playerId, type, action);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		map.put("counts", counts);

		map.put("type", type);
		map.put("action", action);
		map.put("page", page);
		map.put("pageSize", pageSize);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 发送/回复 信件
	 * 
	 * @param session
	 * @param sendMap
	 * @return
	 */
	public ResponseMessage sendMail(Session session, String playerName, String title, String content) {

		if (BlankUtils.isBlank(playerName) || BlankUtils.isBlank(title) || BlankUtils.isBlank(content)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}
		if (AccessInspection.checkChat(session.getUid())) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("chat.err.restricted"));
		}

		Player toPlayer = Context.getPlayerServer().getByPlayerName(playerName);
		if (toPlayer == null)
			return ResponseMessage.ticpErrMsg(LanguageLib.get("mail.err.playername"));

		if (toPlayer.getPlayerId() == session.getUid()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("mail.err.self"));
		}

		int titleLength = title.getBytes(Constants.charset).length;
		if (titleLength < ConstantsConfig.getMailTitleLength() || titleLength > ConstantsConfig.getMailTitleLengthMax()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("mail.err.title"));
		}

		content = StringProcesser.removeHtml(content);
		int contentLength = content.getBytes(Constants.charset).length;
		if (contentLength < ConstantsConfig.getMailContentLength() || contentLength > ConstantsConfig.getMailContentLengthMax()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("mail.err.content"));
		}

		String bad = WordProcesser.chkBadWorlds(title);
		if (!BlankUtils.isBlank(bad)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("mail.err.bad", bad));
		}

		bad = WordProcesser.chkBadWorlds(content);
		if (!BlankUtils.isBlank(bad)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("mail.err.bad", bad));
		}

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (CommInspection.checkSpam(player, content)) {
			return ResponseMessage.errMsg(LanguageLib.get("chat.err.qq"));
		}
		if (CommInspection.checkSpam(player, title)) {
			return ResponseMessage.errMsg(LanguageLib.get("chat.err.qq"));
		}
		if (AccessInspection.isForbidChat(player, title.concat(content))) {
			return ResponseMessage.errMsg(LanguageLib.get("chat.err.qq"));
		}
		Context.getMessageServer().sendMail(toPlayer.getPlayerId(), toPlayer.getPlayerName(), player.getPlayerId(), player.getPlayerName(), title, content);

		return ResponseMessage.ticpMsg(LanguageLib.get("mail.suc.send"));
	}

	/**
	 * 帮派群发消息
	 * 
	 * @param session
	 * @param positions
	 * @param title
	 * @param content
	 * @return
	 */
	public ResponseMessage groupSendMessage(Session session, String title, String content) {

		if (Context.getUnionServer().checkPermission(session.getUid(), Union.GROUPSEND)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("union.groupsend.perm"));
		}

		int titleLength = title.getBytes(Constants.charset).length;
		if (titleLength < ConstantsConfig.getMailTitleLength() || titleLength > ConstantsConfig.getMailTitleLengthMax()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("mail.err.title"));
		}

		content = content.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "").replaceAll("[(/>)<]", "");
		int contentLength = content.getBytes(Constants.charset).length;
		if (contentLength < ConstantsConfig.getMailContentLength() || contentLength > ConstantsConfig.getMailContentLengthMax()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("mail.err.content"));
		}

		String bad = WordProcesser.chkBadWorlds(title);
		if (!BlankUtils.isBlank(bad)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("mail.err.bad", bad));
		}

		bad = WordProcesser.chkBadWorlds(content);
		if (!BlankUtils.isBlank(bad)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("mail.err.bad", bad));
		}

		List<Long> receviers = Context.getUnionServer().getPlayersByPosition(session.getUid());
		if (receviers.isEmpty()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("mail.err.playername"));
		}

		Context.getTimerServer().getScheduledExecutor().execute(new GroupSendTask(session.getUid(), receviers, title, content));

		return ResponseMessage.ticpMsg(LanguageLib.get("mail.suc.send"));
	}

	/**
	 * 收取附件
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage receiveAttachment(Session session, int mailId) {

		Mail mail = mailManager.getReceivedMail(session.getUid(), mailId);

		if (mail == null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}
		Map<String, Object> map = new HashMap<String, Object>();
		if (mail.getAttachment() != null && mail.getAttachment().length() > 0) {

			if (mail.getGetTime() > 0) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("mail.attchment.err"));
			}

			List<SubPops> attachments = null;
			try {
				attachments = JsonProcesser.objectJsonArrayDecode(mail.getAttachment(), SubPops.class);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (attachments != null) {

				Player player = Context.getPlayerServer().getByPlayerId(session.getUid());

				int size = 0;
				for (SubPops ep : attachments) {
					if (ep.getGoodsId() > 0) {
						size++;
					}
				}

				if (!player.getPlayerBoxs().checkBlack(size)) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("mail.attchment.box", size));
				}

				StringBuffer logSb = new StringBuffer();
				Context.getGoodsServer().giveSubPops(attachments, player, logSb, ConstantsCost.gotByMail);
				player.commitSync();

				mailManager.receiveAttachment(player.getPlayerId(), mailId);
				map.put("asset", player.getAsset());
				map.put("exp", player.getExp());
				// 添加“领取礼包”日志
				LogServer.recordLog(player, ConstantsLog.goods, 70010, logSb.toString(), mail.getTitle());
			}

		}
		return ResponseMessage.ticpMsg(LanguageLib.get("comm.suc.exec"), map);
	}

	/**
	 * 读信件
	 * 
	 * @param session
	 * @param id
	 */
	public ResponseMessage readMail(Session session, int type, int id) {

		Mail mail = null;

		if (type == 1) {
			mail = mailManager.getReceivedMail(session.getUid(), id);
		} else {
			mail = mailManager.getSendedMail(session.getUid(), id);
		}

		if (mail == null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		if (mail.getPlayerId() == session.getUid()) {
			mailManager.signReaded(session.getUid(), id);
			mail.setReaded(true);
		}

		// 添加附件
		SubPopsVO awards = null;
		if (!BlankUtils.isBlank(mail.getAttachment())) {
			List<SubPops> attachments = null;
			try {
				attachments = JsonProcesser.objectJsonArrayDecode(mail.getAttachment(), SubPops.class);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (attachments != null) {
				awards = Context.getGoodsServer().makeAwards(attachments);
			}
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("mail", mail.toMailVO(awards));
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 标记已读
	 * 
	 * @param session
	 * @param ids
	 * @return
	 */
	public ResponseMessage signReaded(Session session, String idsStr) {
		int[] ids = StringProcesser.toIntArray(idsStr);
		if (ids.length <= 0)
			return null;
		mailManager.signReaded(session.getUid(), ids);

		return ResponseMessage.ticpMsg(LanguageLib.get("comm.suc.exec"));
	}

	/**
	 * 保存信件
	 * 
	 * @param session
	 * @param id
	 *            编号
	 */
	public ResponseMessage saveMail(Session session, int id) {
		mailManager.saveMail(session.getUid(), id);
		return ResponseMessage.ticpMsg(LanguageLib.get("comm.suc.exec"));
	}

	/**
	 * 删除一组短信
	 * 
	 * @param session
	 * @param ids
	 */
	public ResponseMessage delListMail(Session session, int action, String idsStr) {
		int[] ids = StringProcesser.toIntArray(idsStr);
		if (ids.length <= 0)
			return null;
		mailManager.delMail(session.getUid(), action, ids);
		return ResponseMessage.ticpMsg(LanguageLib.get("comm.suc.exec"));
	}

	/**
	 * 删除某类型全部短信
	 * 
	 * @param session
	 * @param type
	 */
	public ResponseMessage delAllMail(Session session, int action, int type) {
		mailManager.delAll(session.getUid(), action, type);
		return ResponseMessage.ticpMsg(LanguageLib.get("comm.suc.exec"));

	}

}
